<template>
  <div class="alphabet-wrap"
       ref="wrapper">
    <ul class="letter-list"
        @click="handleIndexClick"
        @touchstart="handleTouchStart"
        @touchmove.stop.prevent="handleTouchMove"
        @touchEnd="handleTouchEnd">
      <li class="letter-item"
          v-for="(item,index) of letters"
          :key="item"
          :ref="item"
          :data-index="index"
          :class="{current:currentIndex===index}">
        {{item}}
      </li>
    </ul>
  </div>
</template>

<script>
import { getData } from '@/assets/js/dom'
export default {
  name: 'CityAlphabet',
  props: {
    cities: {
      type: Object
    },
    currentIndex: {
      type: Number
    }
  },
  data () {
    return {
      touchStatus: false,
      startY: 0,
      timer: null
    }
  },
  computed: {
    letters () {
      const letters = []
      for (let key in this.cities) {
        letters.push(key)
      }
      return letters
    }
  },
  updated () {
    this.startY = this.$refs['A'][0].offsetTop
  },
  methods: {
    handleIndexClick (e) {
      const index = getData(e.target, 'index')
      this.$emit('change', index)
    },
    handleTouchStart () {
      this.touchStatus = true
    },
    handleTouchMove (e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          const MoveY = e.touches[0].clientY - 106
          const index = Math.floor((MoveY - this.startY) / 19)
          if (index >= 0 && index < this.letters.length) {
            this.$emit('change', index)
          }
          this.timer = null
        }, 16)
      }
    },
    handleTouchEnd () {
      this.touchStatus = false
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~stylus/variable.styl'

.alphabet-wrap
  position fixed
  top 210px
  right 10px
  display flex
  z-index 1

  .letter-list
    margin-top 90px

    .letter-item
      width 40px
      border-radius 50%
      line-height 40px
      font-size $smallFz
      color $fzColor
      text-align center

    .current
      background-color rgba(0, 0, 0, 0.1)
</style>
